/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GoLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_01_01			*/
/*	File:		GoTcpTest.go			*/
/********************************************************/

package main

import (
	"os"
	. "GoGlb"
	C "GoCls"
	N "GoNet"
)

func main() {
	if len(os.Args) > 1 {
		server()
	} else {
		client()
	}
}

func server() {
	t := new(N.GoTcpSer)
	if nil == t.GoTcpSerListen(N.GO_TP_TCP4, ":12345") {
		for {
			con, err := t.GoTcpSerAccept()
			if nil == err {
				c := &N.GoTcpCon{}
				c.GoTcpConPut(con)
				r := make([]byte, GO_KBYTES1)
				_, err := c.GoTcpConRead(r)
				if nil == err {
					s := "Server: " + string(r)
					_, err := c.GoTcpConWrite([]byte(s))
					if nil != err {
						GoPrint("Failed to GoTcpConWrite\n")
					}
				} else {
					GoPrint("Failed to GoTcpConRead\n")
				}
			} else {
				GoPrint("Failed to GoTcpSerAccept\n")
			}
		}
		t.GoTcpSerClose()
	} else {
		GoPrint("Failed to GoTcpSerListen\n")
	}
}

func client() {
	for i := 0; i < 10; i ++ {
		t := new(N.GoTcpCli)
		s := "Copyright (C) 2016 Gong Li Bin		"
		if nil == t.GoTcpCliDial(N.GO_TP_TCP4, "127.0.0.1:12345") {
			_, e := t.GoTcpCliWrite([]byte(s))
			if nil == e {
				r := make([]byte, GO_KBYTES1)
				_, e := t.GoTcpCliRead(r)
				if nil == e {
					GoPrint("%s\n", string(r))
				} else {
					GoPrint("Failed to GoTcpCliRead\n")
				}
			} else {
				GoPrint("Failure to GoTcpCliWrite\n")
			}
			t.GoTcpCliClose()
		} else {
			GoPrint("Failed to GoTcpCliDial\n")
		}
		C.GoTimeSleep(1, 0)
	}
}
